/*
 * Copyright (c) 2009, David A. Freels Sr.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 * the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *     * Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package net.whippetcode.plugins.intellij.hudson.ui.job;

import net.whippetcode.plugins.intellij.hudson.HudsonMonitorSettings;
import net.whippetcode.plugins.intellij.hudson.domain.job.Status;
import net.whippetcode.plugins.intellij.hudson.parser.sax.SaxJobHandler;
import net.whippetcode.plugins.intellij.hudson.util.LogUtil;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;

/**
 * This class represents the model for the Job control.
 *
 * @author David A. Freels Sr.
 */
public class HudsonJobModel
{
	private JobTreeModel jobTreeModel = new JobTreeModel();
	private URL serverURL;
	private String statusSummary;
	private Status status;
	private URL runUrl;
	private URL testUrl;
	private URL openURL;

	/**
	 * Creates an instance of the model class.
	 *
	 * @param settings Settings information.
	 * @throws MalformedURLException Thrown if a proper URL cannot be constructed.
	 */
	public HudsonJobModel(HudsonMonitorSettings settings) throws MalformedURLException
	{
		update(settings);
	}

	void update(HudsonMonitorSettings settings)
		 throws MalformedURLException
	{
		String serverAddress = settings.getServerAddress();
		if (serverAddress == null)
		{
			serverAddress = "http://localhost";
		}
		serverURL = new URL(serverAddress + (settings.isUseView() ? "/view/" + settings.getViewName().replaceAll(" ", "%20") : "")); // + "/api/xml?depth=2");

	}

	/**
	 * Return a summary of all of the Job status.
	 *
	 * @return A summary of all of the Job status.
	 */
	public String getStatusSummary()
	{
		return statusSummary;
	}

	/**
	 * The overall status of the combined Jobs.
	 *
	 * @return The overall status of the combined Jobs.
	 */
	public Status getStatus()
	{
		return status;
	}

	/**
	 * The URL used to connect to the Hudson server.
	 *
	 * @return The URL used to connect to the Hudson server.
	 */
	public URL getServerURL()
	{
		return serverURL;
	}

	/**
	 * Provides a handle to the model used by the JTree.
	 *
	 * @return A handle to the model used by the JTree.
	 */
	JobTreeModel getJobTreeModel()
	{
		return jobTreeModel;
	}

	/**
	 * Retrieve and parse the Job status from the server.
	 *
	 * @param jobTask												The task that was executed.
	 * @throws IOException									Thrown if a connection cannot be established.
	 * @throws ParserConfigurationException Thrown if the XML cannot be parsed.
	 * @throws XPathExpressionException		 Thrown if an invalid path is used while parsing.
	 * @throws SAXException								 Thrown if a proper XML document is not returned by the server.
	 */
	void loadJobs(PopulateJobsTask jobTask) throws IOException, ParserConfigurationException, XPathExpressionException, SAXException
	{
		PopulateJobsTaskResult result = jobTask.getResult();
		jobTreeModel.setJobs(result.getJobs());
		statusSummary = result.getStatusMessage();
		status = result.getStatus();
	}

	/**
	 * The URL required to run a job.
	 *
	 * @return The URL required to run a job.
	 */
	public URL getRunUrl()
	{
		return runUrl;
	}

	/**
	 * The URL required to retrieve the test information.
	 *
	 * @return The URL required to retrieve the test information.
	 */
	public URL getTestUrl()
	{
		return testUrl;
	}

	/**
	 * The URL required to open a selected Job.
	 *
	 * @return The URL required to open a selected Job.
	 */
	public URL getOpenURL()
	{
		return openURL;
	}

	/**
	 * The URL required to run a job.
	 *
	 * @param runUrl The URL required to run a job.
	 */
	public void setRunUrl(URL runUrl)
	{
		try
		{
			this.runUrl = new URL(runUrl.toString() + "/build?delay=0sec");
		}
		catch (MalformedURLException e)
		{
			LogUtil.log(Level.SEVERE, e.getMessage(), e);
		}
	}

	/**
	 * The URL required to retrieve the test information.
	 *
	 * @param testUrl The URL required to retrieve the test information.
	 */
	public void setTestUrl(URL testUrl)
	{
		this.testUrl = testUrl;
	}

	/**
	 * The URL required to open a selected Job.
	 *
	 * @param openURL The URL required to open a selected Job.
	 */
	public void setOpenURL(URL openURL)
	{
		this.openURL = openURL;
	}
}
